﻿IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'userRoleAdd')
	BEGIN
		DROP  Procedure  userRoleAdd
	END
GO

-- =============================================
-- Author:		<Ricardo Sosa>
-- Create date: <03/03/09>
-- Description:	<Agrega un rol a un usuario>
-- =============================================
CREATE PROCEDURE [dbo].[userRoleAdd]
	-- Add the parameters for the stored procedure here
	@UserName VARCHAR(50),
	@RoleName VARCHAR(50),
	@ApplicationId INT
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

	DECLARE @role_id AS INT;
	DECLARE @user_id AS INT;

	SELECT @role_id = lit_rol_id  
	FROM lit_rol
	WHERE lit_aplicacion_id = @ApplicationId
	AND lit_rol_nombre = @RoleName;

	SELECT @user_id = lit_usuario_id  
	FROM lit_usuario
	WHERE lit_aplicacion_id = @ApplicationId
	AND lit_usuario_username = @UserName;

	IF (NOT EXISTS(	SELECT * 
					FROM lit_usuario_rol 
					WHERE lit_usuario_id = @user_id 
					AND lit_rol_id = @role_id)) BEGIN
		
		INSERT INTO lit_usuario_rol(lit_usuario_id, lit_rol_id) VALUES (@user_id, @role_id);
	END
END
GO